<template>
  <a-form ref="formRef" :model="vdata.currentConfig" layout="vertical" :rules="ifParamsRules">
    <a-row :gutter="16">
      <a-col span="12">
        <a-form-item label="商户编号" name="mchtNo">
          <a-input v-model:value.trim="vdata.currentConfig['mchtNo']" style="width: 330px" />
        </a-form-item>
      </a-col>
      <a-col span="12">
        <a-form-item label="终端编号" name="termNo">
          <a-input v-model:value.trim="vdata.currentConfig['termNo']" style="width: 330px" />
        </a-form-item>
      </a-col>
      <a-col span="12">

        <a-form-item label="激活码" name="authCode">
          <a-input v-model:value.trim="vdata.currentConfig['authCode']" style="width: 330px" />
          <a-input type="hidden" v-model:value.trim="vdata.currentConfig['updateTime']" />
        </a-form-item>
      </a-col>
      <a-col span="12">
        <a-form-item label="获取密钥" name="key">
          <a-input v-model:value.trim="vdata.currentConfig['key']" style="width: 330px" />
          <a-button type="primary" style="margin-left:20px"
              @click="configInterfaceFunc(vdata.currentConfig['mchtNo'], vdata.currentConfig['termNo'], vdata.currentConfig['authCode'])">
            获取密钥
          </a-button>
          <a-button type="primary" style="margin-left:20px"
                    @click="configInterfaceUpdateKeyFunc(vdata.currentConfig['mchtNo'], vdata.currentConfig['termNo'], vdata.currentConfig['key'])">
            更新密钥
          </a-button>
        </a-form-item>
      </a-col>
    </a-row>
  </a-form>
</template>
<script setup lang="ts">
import { upload,$queryKeyByAuthCode,$updateKey } from '@/api/manage'
import { ref, reactive, defineExpose, inject,getCurrentInstance } from 'vue'

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const vdata = reactive ({
  mchType: 1, //商户类型
  isAdd: true,
  ifDefineArray: [], // 接口的配置定义项数组
  currentConfig: {} as any, // 当前配置项
  liteConfig: {} as any, // 小程序配置项
  activeKey: ['1'], // 折叠默认展开
  action: upload.cert, // 上传文件地址
  encryptionField : { // 定义加密的字段
    privateKey: '',
    alipayPublicKey: ''
  },

})

const ccbpayAuthRef = ref()

//表单规则
const ifParamsRules = reactive({
         mchtNo: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (!value) {
              return Promise.reject(new Error('请输入商户编号'))
            }
            return Promise.resolve()
         } }],
         termNo: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (!value) {
              return Promise.reject(new Error('请输入终端编号'))
            }
            return Promise.resolve()
         } }],
         authCode: [{ trigger: 'blur',
          validator: (rule, value) => {
            if (!value) {
              return Promise.reject(new Error('请输入激活码'))
            }
            return Promise.resolve()
         } }]
      })

// 当前的form
const formRef = ref()

function configInterfaceFunc(mchtNo, termNo, authCode) {
  if(!mchtNo){
    $infoBox.message.error('请填写商户编号!')
    return Promise.reject()
  }
  if(!termNo){
    $infoBox.message.error('请填写终端编号!')
    return Promise.reject()
  }
  if(!authCode){
    $infoBox.message.error('请填写激活码!')
    return Promise.reject()
  }
  $queryKeyByAuthCode(mchtNo,termNo,authCode).then((res) => {
    vdata.currentConfig['key'] = res.key;
  }).catch(() => {
    return Promise.resolve()
  })
}

function configInterfaceUpdateKeyFunc(mchtNo, termNo, key) {
  if(!mchtNo){
    $infoBox.message.error('请填写商户编号!')
    return Promise.reject()
  }
  if(!termNo){
    $infoBox.message.error('请填写终端编号!')
    return Promise.reject()
  }
  if(!key){
    $infoBox.message.error('请输入原密钥!')
    return Promise.reject()
  }
  $updateKey(mchtNo,termNo,key).then((res) => {
    vdata.currentConfig['key'] = res.key;
  }).catch(() => {
    return Promise.resolve()
  })
}


function getConfigParams(){
  return formRef.value.validate().then( () => {
    return convertEncryData()
  })

}

// 转换数据
function convertEncryData(){
  // 对象克隆
  let result = Object.assign({}, vdata.currentConfig)
  return result
}

// 对外提供的页面的渲染函数 （ ifDefineArray = 接口的配置定义项数组，  currentConfig = 当前配置项,mchType=商户类型 ）
// 20230918 新增： isProcessStarField = true ( 是否处理 脱敏数据， 默认为 true  )
function pageRender(ifDefineArray, currentConfig, mchType, isProcessStarField = false){
  // 赋值
  vdata.mchType = mchType
  vdata.currentConfig = {...currentConfig,updateTime:new Date().getTime()}

  // 处理加密数据字段
  if(isProcessStarField){
    Object.keys(vdata.encryptionField).forEach(key => {
      vdata.encryptionField[key] = vdata.currentConfig[key]
      delete vdata.currentConfig[key]
    })
  }

  // 重置form验证
  if (formRef.value !== undefined && formRef.value !== null) {
    formRef.value.resetFields()
  }

}

// 消除参数空格
function changeFun(value) {
  if(vdata.currentConfig[value]) {
    vdata.currentConfig[value] = vdata.currentConfig[value].trim()
  }
}

defineExpose({ getConfigParams, pageRender })

</script>
